package cn.org.xiaoweiba.graduationdesign.bookmall.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis 配置类
 */
@Configuration
public class RedisConfig {

    /**
     * 向 spring 容器中添加设置了指定的键值序列化器的 redisTemplate
     *
     * @param redisConnectionFactory redis 连接工厂
     * @return redisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 创建 redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 设置 redis 连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置键值序列化器，避免 redis 中乱码
        // 设置键序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // 设置值序列化器
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 返回 redisTemplate
        return redisTemplate;
    }

}
